<script setup>
import { defineAsyncComponent } from "vue";
import VideoPlayGlobalModal from "@/components/VideoPlayGlobalModal/index.vue";
import { useVideoPlayerStore } from "@/store/modules/videoPlayer";
import { useUserStore } from "@/store/modules/user";
// 动态导入 AuthModal 组件
const AuthModal = defineAsyncComponent(() =>
  import("./components/AuthModal/index.vue")
);

const videoPlayerStore = useVideoPlayerStore();
const userStore = useUserStore();

const handleVideoUpdate = (updatedVideo) => {
  // 检查是否是视频切换请求
  if (updatedVideo.videoObj) {
    console.log("App 收到视频切换请求:", {
      id:
        updatedVideo.id ||
        updatedVideo.videoObj?.id ||
        updatedVideo.videoObj?.video_id,
      title: updatedVideo.videoObj?.title,
    });

    // 标准化ID
    const videoId = String(
      updatedVideo.id ||
        updatedVideo.videoObj?.id ||
        updatedVideo.videoObj?.video_id
    );

    // 确保有效的视频ID
    if (videoId) {
      videoPlayerStore.switchVideo(videoId, updatedVideo.videoObj);
    } else {
      console.error("无效的视频ID，无法切换");
    }
    return;
  }

  // 否则是常规更新
  if (updatedVideo && updatedVideo.id) {
    videoPlayerStore.updateVideoState(updatedVideo);
  }
};
</script>

<template>
  <div class="box">
    <RouterView />
    <AuthModal v-if="userStore.isAuthModalOpen" />
    <!-- 全局视频播放模态框 -->
    <VideoPlayGlobalModal
      :show="videoPlayerStore.isModalVisible"
      :video-id="videoPlayerStore.currentVideoId"
      :video="videoPlayerStore.currentVideo"
      @close="videoPlayerStore.closeVideoModal()"
      @updateVideo="handleVideoUpdate"
    />
  </div>
</template>

<style scoped lang="scss">
.box {
  height: 100%;
  width: 100%;
}
</style>
